package com.dkm.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.dkm.entity.SongList;
import com.dkm.repository.SongListRepository;
import com.dkm.service.SongListService;
import com.dkm.util.MusicUtil;

@Service
public class SongListServiceImpl implements SongListService {

	//注入歌单持久层
	@Autowired
	private SongListRepository songListRepository;
	
	@Override
	public List<MusicUtil> getSongsByUser_id(String user_id) {
		
		List<MusicUtil> musics=new ArrayList<MusicUtil>();
		//根据用户id获取歌曲
		List<SongList> songs=songListRepository.getSongsByUser_id(user_id);
		for (SongList song : songs) {
			MusicUtil musicUtil=new MusicUtil();
			musicUtil.setId(song.getSongId());
			musicUtil.setTitle(song.getTitle());
			musicUtil.setArtist(song.getArtist());
			musicUtil.setMp3(song.getUrl());
			musicUtil.setPoster(song.getPoster());
			//加入集合中
			musics.add(musicUtil);
		}
		
		return musics;
	}

	@Override
	public Page<SongList> getAllSongList(Map<String, Object> map, Pageable pageable) {
		
		return songListRepository.findAll(this.get(map), pageable);
	}

	private Specification<SongList> get(Map<String, Object> map) {
		return new Specification<SongList>() {
			
			@Override
			public Predicate toPredicate(Root<SongList> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				//1、创建Predicate对象,动态sql表达式
				Predicate predicate=criteriaBuilder.conjunction();
				//2、创建一个集合，存放多个条件,动态sql表达式集合
				List<Expression<Boolean>> expressions=predicate.getExpressions();
				
				//用户编号
				if(!StringUtils.isEmpty(map.get("user_id"))) {
					expressions.add(criteriaBuilder.equal(root.get("user").get("user_id"), map.get("user_id")));
				}
				
				return predicate;
			}
		};
	}

}
